import numpy as np


class NeutronNetworkModel:
    """
    自定义神经网络模型
    """

    def __init__(self):
        """
        构造器/构造函数，保存模型的层
        """
        # 深度学习网络层列表
        self.__layers = []

    def add_layer(self, layer):
        """
        将层追带到最后
        :param layer:
        :return:
        """
        self.__layers.append(layer)

    def train(self, X_train, X_test, y_train, y_test, learning_rate, max_epochs):
        """
        模型的训练
        :param X_train: 训练数据
        :param X_test: 测试数据
        :param y_train: 训练数据标签
        :param y_test: 测试数据标签
        :param max_epoch: 最大的迭代数量
        :return:
        """
        # one-hot 编码
        y_onehot = np.zeros((y_train.shape[0], 2))
        y_onehot[np.arange(y_train.shape[0]), y_train] = 1

        # print(y_onehot)
        # 将One-hot 编码后的真实标签与网络的输出计算均方误差，并调用反向传播函数更新网络参数，循环迭代训练集1000 遍即可
        mses = []  # 每次迭代都会保存均方差
        accuracys = []  # 准确率
        for i in range(max_epochs + 1):  # 训练1000 个epoch
            for j in range(len(X_train)):  # 一次训练一个样本
                self.backpropagation(X_train[j], y_onehot[j], learning_rate)
            if i % 10 == 0:
                # 打印出MSE Loss
                mse = np.mean(np.square(y_onehot - self.feed_forward(X_train)))

                accuracy = self.accuracy(self.predict(X_test), y_test.flatten())
                # 当前的准确和上一次准确率偏差如果小于 0.0001，结束 训练
                # if (len(accuracys) > 0) and (abs(accuracys[-1] - accuracy) < 0.0005):
                #     break
                # 利用准确率空值迭代的结束
                if accuracy > 0.87:
                    break
                mses.append(mse)
                accuracys.append(accuracy)

                print('Epoch: #%s, MSE: %f' % (i, float(mse)))
                # 统计并打印准确率
                print('Accuracy: %.2f%%' % (accuracy * 100))
        return mses, accuracys

    def backpropagation(self, X, y, learning_rate):
        # 反向传播算法实现
        # 前向计算，得到最终输出值
        output = self.feed_forward(X)
        for i in reversed(range(len(self.__layers))):  # 反向循环
            layer = self.__layers[i]  # 得到当前层对象
            # 如果是输出层
            if layer == self.__layers[-1]:  # 对于输出层
                layer.error = y - output  # 计算2 分类任务的均方差的导数
                # 关键步骤：计算最后一层的delta，参考输出层的梯度公式
                layer.delta = layer.error * layer.apply_activation_derivative(output)
            else:  # 如果是隐藏层
                next_layer = self.__layers[i + 1]  # 得到下一层对象
                layer.error = np.dot(next_layer.weights, next_layer.delta)
                # 关键步骤：计算隐藏层的delta，参考隐藏层的梯度公式
                layer.delta = layer.error * layer.apply_activation_derivative(layer.last_activation)

        # 循环更新权值
        for i in range(len(self.__layers)):
            layer = self.__layers[i]
            # o_i 为上一网络层的输出
            o_i = np.atleast_2d(X if i == 0 else self.__layers[i - 1].last_activation)
            # 梯度下降算法，delta 是公式中的负数，故这里用加号
            layer.weights += layer.delta * o_i.T * learning_rate

    # 网络的前向传播只需要循环调各个网络层对象的前向计算函数即可，代码如下：

    def feed_forward(self, X):
        """
        前向传播,将输入输入依次通过每一层
        :param X:
        :return:
        """
        for layer in self.__layers:
            # 依次通过各个网络层
            X = layer.activate(X)
        return X

    def predict(self, X):
        return self.feed_forward(X)

    def accuracy(self, X, y):
        return np.sum(np.equal(np.argmax(X, axis=1), y)) / y.shape[0]
